<template>
  <div class="chart-container">
    <div ref="chart" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'PieChart',
  props: {
    chartData: {
      type: Object,
      default: () => ({}),
    },
    chartOptions: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      chart: null,
      observer: null,
    }
  },
  mounted() {
    this.initChart()
    this.initResizeObserver()
  },
  methods: {
    initChart() {
      if (this.chart) {
        this.chart.dispose()
      }
      this.chart = echarts.init(this.$refs.chart)

      const option = {
        title: {
          text: '饼图示例',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: 1048, name: '搜索引擎' },
              { value: 735, name: '直接访问' },
              { value: 580, name: '邮件营销' },
              { value: 484, name: '联盟广告' },
              { value: 300, name: '视频广告' },
            ],
          },
        ],
      }

      this.chart.setOption({ ...option, ...this.chartOptions })
    },
    initResizeObserver() {
      this.observer = new ResizeObserver(() => {
        if (this.chart) {
          this.chart.resize()
        }
      })
      this.observer.observe(this.$refs.chart)
    },
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)
  },
  watch: {
    chartData: {
      handler(newValue) {
        if (this.chart && newValue) {
          this.chart.setOption(newValue)
        }
      },
      deep: true,
    },
  },
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  padding: 10px;
  background: transparent;
  position: relative;
}

.chart-content {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style> 